extends Area2D

class_name BlockUnit

signal position_changed(new_position)
signal landed
signal drag_started
signal drag_ended

@export var block_size: Vector2 = Vector2(100, 100)  # 方块尺寸
@onready var sprite = $Sprite2D
@onready var collision_shape = $CollisionShape2D

var is_dragging: bool = false
var drag_offset: Vector2 = Vector2.ZERO
var texture: Texture2D

func _ready():
	# 初始化碰撞形状
	var rect_shape = RectangleShape2D.new()
	rect_shape.size = block_size
	collision_shape.shape = rect_shape
	
	# 设置精灵尺寸
	sprite.scale = block_size / sprite.texture.get_size() if sprite.texture else Vector2.ONE
	
	# 连接输入事件
	input_event.connect(_on_input_event)

func set_texture(new_texture: Texture2D) -> void:
	texture = new_texture
	sprite.texture = texture
	# 调整精灵缩放以适应方块尺寸
	sprite.scale = block_size / texture.get_size()

func is_block() -> bool:
	return true

func _on_input_event(viewport: Viewport, event: InputEvent, shape_idx: int) -> void:
	# 鼠标按下
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed:
			start_drag(get_global_mouse_position())
		else:
			end_drag(get_global_mouse_position())
	
	# 触摸按下
	elif event is InputEventScreenTouch:
		if event.pressed:
			start_drag(event.position)
		else:
			end_drag(event.position)
	
	# 触摸拖动
	elif event is InputEventScreenDrag and is_dragging:
		update_drag_position(event.position)

func start_drag(global_pos: Vector2) -> void:
	is_dragging = true
	drag_offset = global_position - global_pos
	drag_started.emit()
	get_parent().get_node("fall_timer").stop()

func end_drag(global_pos: Vector2) -> void:
	if is_dragging:
		is_dragging = false
		update_drag_position(global_pos)
		drag_ended.emit()
		landed.emit()

func update_drag_position(global_pos: Vector2) -> void:
	var new_global_pos = global_pos + drag_offset
	var new_local_pos = get_parent().to_local(new_global_pos)
	position = new_local_pos
	position_changed.emit(position)

func _physics_process(delta: float) -> void:
	if is_dragging:
		# 鼠标拖动更新
		if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
			update_drag_position(get_global_mouse_position())
